
package com.hmsg.health.controller;


import com.hmsg.health.bean.vo.*;
import com.hmsg.health.dao.AppealDao;
import com.hmsg.health.dao.InviteDao;
import com.hmsg.health.dao.OrderDao;
import com.hmsg.health.dao.UserAccountDao;
import com.hmsg.health.dao.UserAccountRecordDao;
import com.hmsg.health.dao.UserDao;
import com.hmsg.health.service.MenWangSMSService;
import com.hmsg.health.service.UserService;
import com.hmsg.health.service.aes.SecurityData;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSBuilder;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.http.HttpResponse;
import com.hmsg.health.bean.domain.BannerDo;
import com.hmsg.health.bean.domain.InviteDo;
import com.hmsg.health.bean.domain.SorderDo;
import com.hmsg.health.bean.domain.UserAccountDo;
import com.hmsg.health.bean.domain.UserAccountRecordDo;
import com.hmsg.health.bean.domain.UserDo;
import com.hmsg.health.bean.enums.StatusCode;
import com.hmsg.health.config.Constants;
import com.hmsg.health.config.PropertyConfig;
import com.hmsg.health.param.AccessToken;
import com.hmsg.health.param.ResponseResult;
import com.hmsg.health.security.IgnoreSecurity;
import com.hmsg.health.security.OpenApi;
import com.hmsg.health.security.TokenManager;
import com.hmsg.health.utils.ApiException;
import com.hmsg.health.utils.ErrorCode;
import com.hmsg.health.utils.GetScene;
import com.hmsg.health.utils.HttpResult;
import com.hmsg.health.utils.HttpUtil;
import com.hmsg.health.utils.IdWorker;
import com.hmsg.health.utils.RandomUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/pay")
@Api(value="ApplePayController",description="苹果支付")
public class ApplePayController {
	// 购买凭证验证地址
	private static final String verifyReceiptUrl = "https://buy.itunes.apple.com/verifyReceipt";
	// 测试的购买凭证验证地址
	private static final String verifyReceiptUrlSandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
	
	private static int requestCounts = 0;
	@Autowired
	private UserAccountDao userAccountDao;
	
	@Autowired
	private UserAccountRecordDao userAccountRecordDao;
	/**
	 * 重写X509TrustManager
	 */
	private static TrustManager myX509TrustManager = new X509TrustManager() {
		

		

		@Override
		public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
			// TODO Auto-generated method stub
			
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return null;
		}
	};
	
	@Autowired
	private OrderDao orderDao;

	/**
	 * 接收iOS端发过来的购买凭证
	 * 
	 * @param url
	 * @param strings
	 * @return
	 */
	@ApiOperation(value="接收iOS端发过来的购买凭证",httpMethod="POST",notes="接收iOS端发过来的购买凭证")
    @PostMapping("/iap")
	@ResponseBody
	@IgnoreSecurity
	@OpenApi
	@SecurityData
	private ResponseResult<Object> sendHttpsCoon(
			@RequestHeader(Constants.CLIENT_USER) Integer userId,
			@RequestBody @Validated ApplePayVo vo) {
		if ( null == vo.getReceipt() ) {
			return new ResponseResult<Object>(StatusCode.VERIFY_ERROR , null);
		} else {
			System.out.println(vo.getReceipt());
			String url = vo.getChooseEnv()==1 ? verifyReceiptUrl : verifyReceiptUrlSandbox;
			try {
				// 设置SSLContext
				SSLContext ssl = SSLContext.getInstance("SSL");
				ssl.init(null, new TrustManager[] { myX509TrustManager }, null);

				// 打开连接
				HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
				// 设置套接工厂
				conn.setSSLSocketFactory(ssl.getSocketFactory());
				// 加入数据
				conn.setRequestMethod("POST");
				conn.setRequestProperty("Content-type", "application/json");
				conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
//				conn.setDoInput(true);
				conn.setDoOutput(true);
				JSONObject obj = new JSONObject();
				obj.put("receipt-data", vo.getReceipt());
				// 获取输出流
				BufferedOutputStream buffOutStr = new BufferedOutputStream(conn.getOutputStream());
				buffOutStr.write(obj.toString().getBytes());
				buffOutStr.flush();
				buffOutStr.close();
				// 获取输入流
				BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				String line = null;
				StringBuffer sb = new StringBuffer();
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				//苹果返回的string
				String stringadsf = sb.toString();
				conn.getInputStream().close();
				com.alibaba.fastjson.JSONObject job = com.alibaba.fastjson.JSONObject.parseObject(stringadsf);// App Store的返回值
				System.out.println("jjjjjjjjjjjj-----------"+job);
				if (job.getInteger("status")==0) {
					// 跟苹果验证有返回结果--验证成功
					com.alibaba.fastjson.JSONObject code = com.alibaba.fastjson.JSONObject.parseObject(job.getString("receipt"));
					String creation_date_ms = code.getString("receipt_creation_date_ms"); // receipt创建日期(ms)
					JSONArray jsonArray = (JSONArray) code.get("in_app");// 订单列表
					com.alibaba.fastjson.JSONObject targetOrder = null;
					if (1 == jsonArray.size()) {
						// 订单列表为一个,直接取出
						targetOrder = jsonArray.getJSONObject(0);
					} else{
						// 订单列表为多个,根据支付订单创建时间戳获取本次订单 
						
						for (int i = 0; i < jsonArray.size(); i++) {
							com.alibaba.fastjson.JSONObject orderItem = jsonArray.getJSONObject(i);
							if (orderItem.getString("purchase_date_ms").equals(creation_date_ms)) {
								targetOrder = orderItem;
							}
						}
					}
					if (null == targetOrder) {
						System.out.println("验证结果中不存在订单信息 " );
					} else {
						System.out.println("11111111--------------"+code);
						
						//获取apple_product_id
						String product_id = targetOrder.getString("product_id");
						// String money = product_id.substring(4, product_id.length());
						String transaction_id = targetOrder.getString("transaction_id");// transaction_id交易号
						//将凭证解析出的购买信息和本地服务端作对比
						//更新order数据库
						Integer price = 0;
						String goodsName = "商品名称";
						Integer count  =0;
						if(product_id.equals("3")) {
							price = 600;
							count=6000;
							goodsName = "6000金币";
						} else if(product_id.equals("2")) {
							price = 1200;
							count=12000;
							goodsName = "12000金币";
						} else if(product_id.equals("4")) {
							price = 1800;
							count=18000;
							goodsName = "18000金币";
						}else if(product_id.equals("5")) {
							price = 2500;
							count=25000;
							goodsName = "25000金币";
						}else if(product_id.equals("6")) {
							price = 3000;
							count=30000;
							goodsName = "30000金币";
						}else{
							price = 4000;
							count=40000;
							goodsName = "40000金币";
						}
						SorderDo so = new SorderDo();
						so.setAmount(price);
						so.setCreateTime(new Date());
						so.setPayTime(new Date());
						so.setGloadCount(count);
						so.setOrderNum(transaction_id);
						so.setStatus(1);
						so.setGoodsId(Integer.parseInt(product_id));
						so.setUserId(userId);
						int res = orderDao.save(so);
						
						UserAccountDo ua = userAccountDao.findUserAccount(userId);
						ua.setGlod(ua.getGlod()+count);
						
						userAccountDao.update(ua);
						
						UserAccountRecordDo uar = new UserAccountRecordDo();
						uar.setAmount(count);
						uar.setGlodType(1);
						uar.setCreateTime(new Date());
						uar.setTitle("用户充值");
						uar.setUserId(userId);
						userAccountRecordDao.save(uar);
						
						return new ResponseResult<Object>(StatusCode.SYSTEM_SUCCESS, res);
					}
					
				} else if (job.getInteger("status")==21007) {
					return new ResponseResult<Object>(StatusCode.SANDBOX_ERROR, null);
				}  else if (job.getInteger("status")==21008 && requestCounts < 5) {
					return new ResponseResult<Object>(StatusCode.RECEIPT_ERROR, null);
				} else {
					return new ResponseResult<Object>(StatusCode.VERIFY_ERROR , null);
					//Log4jUtil.CommonLog.error("苹果没有返回的验证信息 " );
					//return super.renderError("验证支付信息失败-2", 500);
				}
			} catch (Exception e) {
				return new ResponseResult<Object>(StatusCode.VERIFY_ERROR , null);
			}
		}
		return null;
	}
	}

